﻿// ===============================================================================
// Copyright(c) 2007-2020 西安交通信息投资营运有限公司 版权所有
// ===============================================================================

using System;
using System.Threading.Tasks;
using XCI.Core;
using XCI.Extensions;
using XCI.Sys.Filter;
using XCI.Sys.Model;
using XCI.Sys.Service;
using XCI.Windows;
using XCI.Helper;

namespace XCI.Sys.Forms
{
    /// <summary>
    /// 系统机构管理
    /// </summary>
    [FormCaption("系统机构管理")]
    public partial class FrmDeptManager : BaseForm
    {
        private readonly bool allowSelect = SysApp.Permit("sys.dept.select");
        private readonly bool allowInsert = SysApp.Permit("sys.dept.insert");
        private readonly bool allowUpdate = SysApp.Permit("sys.dept.update");
        private readonly bool allowDelete = SysApp.Permit("sys.dept.delete");
        private readonly bool allowExport = SysApp.Permit("sys.dept.export");

        public FrmDeptManager()
        {
            InitializeComponent();
            tree.ModelType = typeof(SysDept);
        }

        private Task LoadAsync()
        {
            return Mutex.EndAsync(() => tree.LoadAsync());
        }

        private void ShowEditForm(EditFormArgs args)
        {
            var editForm = new FrmDeptEdit(args);
            editForm.ShowDialogOk(async () => await tree.LoadAsync());
        }

        /// <summary>
        /// 页面初始化
        /// </summary>
        private async void FrmDeptManager_Load(object sender, EventArgs e)
        {
            tree.StateImageList = SysDeptService.Instance.GetDeptImageCollection();
            Mutex.Begin(() => filterEditStatus.SelectedIndex = 0);
            await LoadAsync();
            tree.ExpandFirstNode();
        }

        private void Tree_GetStateImage(object sender, DevExpress.XtraTreeList.GetStateImageEventArgs e)
        {
            e.NodeImageIndex = 0;
        }

        private void btnNew_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            ShowEditForm(EditFormArgs.CreateTree(tree.SelectedId));
        }

        private void btnEdit_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            ShowEditForm(EditFormArgs.EditTree(tree.SelectedId, ((SysDept)tree.Selected).ParentId));
        }

        private async void btnCopy_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            if (MessageBoxHelper.ShowWarnYesNo("确定要复制当前选中的数据吗?") != System.Windows.Forms.DialogResult.Yes) return;
            await SysDeptService.Instance.CopyAsync(tree.SelectedId);
            await LoadAsync();
        }

        private async void btnDelete_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            await tree.DeleteCheckedAsync();
        }

        private void btnProperty_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            new FrmDeptDetails(tree).ShowDialogOk();
        }

        private async void btnExport_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            var filter = tree.GetFilter();
            await App.Excel.ExportFileDialogAsync((path, fields) => SysDeptService.Instance.ExportAsync(path, filter as SysDeptFilter), "系统机构列表", this);
        }

        private async void btnRefreshCache_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            await SysDeptService.Instance.RefreshCacheAsync();
            await tree.LoadAsync();
            MessageBoxHelper.ShowMessage("缓存刷新成功");
        }

        private async void repositoryEditStatus_CheckedChanged(object sender, EventArgs e)
        {
            var edit = tree.ActiveEditor;
            var col = tree.FocusedColumn;
            if (col.FieldName.Equals(nameof(SysDept.Status)))
            {
                await SysDeptService.Instance.UpdateStatusAsync(tree.SelectedId, edit.EditValue.ToBool());
            }
        }

        private void Tree_LoadData(object sender, XCI.Windows.LoadTreeDataEventArgs e)
        {
            e.Task = async () => await SysDeptService.Instance.SelectListAsync(e.Filter as SysDeptFilter);
        }

        private void Tree_DetectFilter(object sender, XCI.Windows.DetectTreeFilterObjectEventArgs e)
        {
            e.Filter = App.ContainerData.GetModel(layoutGroupFilter, new SysDeptFilter());
        }

        private void Tree_DeleteData(object sender, XCI.Windows.DeleteDataEventArgs e)
        {
            e.Task = () => SysDeptService.Instance.DeleteAsync(tree.CheckedIds);
        }

        private void Tree_RowSelectionChanged(object sender, EventArgs e)
        {
            var isSingle = !tree.HasMultiSelected && !tree.HasMultiChecked && tree.HasSelected;
            btnNew.Enabled = allowInsert;
            btnEdit.Enabled = isSingle && allowUpdate;
            btnCopy.Enabled = isSingle && allowInsert;
            btnDelete.Enabled = tree.HasChecked && allowDelete;
            btnRefreshCache.Enabled = allowSelect;
            btnExport.Enabled = tree.HasData && allowExport;
            btnProperty.Enabled = isSingle;
        }

        private async void Tree_NodeDragChangedChanged(object sender, XCI.Windows.NodeDragChangedEventArgs e)
        {
            await SysDeptService.Instance.UpdateDndAsync(e.ChangedData);
        }

        private async void statusCombo_SelectedIndexChanged(object sender, EventArgs e)
        {
            await LoadAsync();
            tree.ExpandFirstNode();
        }

        private async void BtnSearch_Click(object sender, EventArgs e)
        {
            await LoadAsync();
            tree.ApplyFindFilter(filterEditKey.Text.Trim());
        }

        private async void BtnReset_Click(object sender, EventArgs e)
        {
            Mutex.Begin(() => App.ContainerData.SetModel(layoutGroupFilter, SysDeptFilter.Default));
            await LoadAsync();
        }

    }
}